# -*- coding: utf-8 -*-
# Create your views here.

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist

from django.http import HttpResponse

from django.contrib.auth.models import User
from paniersApp.models import Participant, jours_de_distribution, Jour, Group

import datetime
import logging

def index(request):
    return HttpResponse("Hello, world. You're at the Paniers index.")

@login_required
def participant(request):
    u = request.user.user
    #print u
    try:
        p = u.participant_set.get()
    except ObjectDoesNotExist:
        return redirect('/', permanent=True)
        
    groupes = p.groupes.all()
    types = [t.nom for t in p.types_paniers.all()]
    jours = jours_de_distribution(p.debut, p.fin, 5)
    
    tblx = []
    tbl_idx = 0
    dates = []
    dispo = []
    panier =[]
    for j in jours:
      dis = sel1 = sel2 = ''
      d = j.strftime('%d/%m/%y')
      dates.append(d)
      _jours = Jour.objects.filter(participant=p, date=j)
      if len(_jours) == 0: #on a pas trouve d'info dans la db
        sel1 = sel2 = ' checked'
      else:
        jour = _jours[0]
        if jour.etat == 1:
          sel1 = ' checked'
        if jour.panier:
          sel2 = ' checked'
      if j < datetime.date.today():
        dis = ' disabled'
      dispo.append('<input type="checkbox" class="participant_ajax" date="{0:02d}{1:02d}{2:02d}" id="dispo_{0:02d}{1:02d}{2:02d}"{3}{4}>'.format(j.year, j.month, j.day, sel1, dis))
      panier.append('<input type="checkbox" class="participant_ajax" date="{0:02d}{1:02d}{2:02d}" id="panier_{0:02d}{1:02d}{2:02d}"{3}{4}>'.format(j.year, j.month, j.day, sel2, dis))

      tbl_idx += 1
      if tbl_idx > 8:
        tblx.append({'dates': dates, 'dispo': dispo, 'panier': panier})
        dates = []
        dispo = []
        panier =[]
        tbl_idx = 0
    logging.debug(tblx)
    #print tblx
    return render(request, 'participant.html', {'p':p.user.all(), 'jours':jours, 'groupes': groupes, 'types': types, 'tblx': tblx})

@login_required
def listpaniers(request, annee, mois, jour):
    date = datetime.datetime(int(annee), int(mois), int(jour))
    u = request.user.user
    #print u
    try:
      p = u.participant_set.get()
    except ObjectDoesNotExist:
      return redirect('/', permanent=True)
    groupes = p.groupes.filter(distrib=True)
    s={}
    for g in groupes:
      s[g.nom] = {}
      distrib_members = Participant.objects.filter(groupes=g).filter(debut__lt=date).filter(fin__gt=date)
      for t in g.types_paniers.all():
        s[g.nom][t.nom] = []
        for d in distrib_members.filter(types_paniers=t):
          s[g.nom][t.nom].append(d.__str__())
        if len(s[g.nom][t.nom]) == 0:
          del(s[g.nom][t.nom])
    return render(request, 'liste_distrib.html', {'s':s})
    
@login_required
@csrf_exempt
def participant_change(request):
  if request.method == 'POST':
    print request.POST
    date = request.POST['date']
    dispo = request.POST['dispo'] == 'true'
    panier = request.POST['panier'] == 'true'
    print date, dispo, panier

    u = request.user.user
    #print u
    try:
      p = u.participant_set.get()
    except ObjectDoesNotExist:
      return redirect('/', permanent=True)
    date = datetime.datetime(int(date[:4]), int(date[4:6]), int(date[6:8]))
    if dispo:
      etat = 1
    else:
      etat = 2
    try:
      jours = Jour.objects.get(participant=p, date=date)
      jours.etat = etat
      jours.panier = panier
      jours.save()
    except ObjectDoesNotExist:
      jours = Jour(participant=p, date=date, etat=etat, panier=panier)
      jours.save()
    print p, date
    return HttpResponse(date)
  